package org.jash.apps.ui

import android.app.usage.ExternalStorageStats
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.view.LayoutInflater
import android.widget.Toast
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import kotlinx.coroutines.launch
import org.jash.apps.R
import org.jash.apps.adapter.CategoryAdapter
import org.jash.apps.databinding.ActivityNetAppsBinding
import org.jash.apps.databinding.DialogProgressBinding
import org.jash.apps.model.AppIntent
import org.jash.apps.model.AppState
import org.jash.apps.model.AppViewModel
import org.jash.common.log.logDebug
import org.jash.common.mvi.BaseActivity
import org.jash.common.mvi.BaseState
import java.io.File

@Route(path = "/apps/net")
class NetAppsActivity : BaseActivity<ActivityNetAppsBinding, AppViewModel>() {
    val downDir by lazy { getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) }
    var userId:Int = 1
    val progressBinding by lazy { DialogProgressBinding.inflate(LayoutInflater.from(this)) }
    val dialog by lazy { MaterialAlertDialogBuilder(this)
        .setView(progressBinding.root)
        .create().apply {
            setCanceledOnTouchOutside(false)
        }
    }
    private val adapter:CategoryAdapter by lazy { CategoryAdapter() }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        lifecycleScope.launch {
            viewModel.intent.send(AppIntent.LoadApps(userId))
        }
        progressBinding.cancel.setOnClickListener {
            lifecycleScope.launch {
                viewModel.intent.send(AppIntent.CancelDownload)
            }
        }
        adapter.setOnClickListener {
            lifecycleScope.launch {
                viewModel.intent.send(AppIntent.DownloadApp(it.apkUrl, File(downDir, "${it.appName}.apk")))
                progressBinding.progress.progress = 0
                dialog.show()
            }
        }
        binding.recycler.adapter = adapter
    }
    fun loadedApps(response: AppState.Response) {
        adapter += response.data
    }
    fun error(error: BaseState.Error) {
        Toast.makeText(this, error.msg, Toast.LENGTH_SHORT).show()
        if (dialog.isShowing) {
            dialog.cancel()
        }
        logDebug(error.msg)
    }
    fun downProgress(progress:AppState.DownProgress) {
        logDebug("下载进度: ${progress.v * 100}%")
        progressBinding.progress.progress = (progress.v * 100).toInt()
    }
    fun downComplete(complete:AppState.DownComplete) {
        logDebug("下载完成")
        progressBinding.progress.progress = 100
        dialog.cancel()
        Toast.makeText(this, "安装成功", Toast.LENGTH_SHORT).show()
    }
}